package com.zzh.lib.views.vp;


import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.zzh.lib.dialog.R;
import com.zzh.lib.views.adapter.HBaseViewPagerAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

/**
 * Created by ZZH on 2022/8/9.
 *
 * @Date: 2022/8/9
 * @Email: zzh_hz@126.com
 * @QQ: 1299234582
 * @Author: zzh
 * @Description: 自动轮播, 一侧卡片重叠。
 */
public class HOverlapCardViewPager<T> extends ViewPager implements LifecycleObserver {
    private boolean isLooping;

    private final Handler mHandler = new Handler(Looper.getMainLooper());

    private final Runnable mRunnable = this::handlePosition;
    private boolean isAutoPlay = false;

    private boolean stopLoopWhenDetachedFromWindow = true;


    private HBaseViewPagerAdapter<T> mBannerPagerAdapter;
    private long mInterval = 5000;

    public boolean isAutoPlay() {
        return isAutoPlay;
    }

    /**
     * 是否自动轮播
     *
     * @param autoPlay true 自动轮播
     */
    public void setAutoPlay(boolean autoPlay) {
        isAutoPlay = autoPlay;
    }

    private void handlePosition() {
        if (mBannerPagerAdapter != null && mBannerPagerAdapter.getListSize() > 1 && isAutoPlay()) {
            setCurrentItem(getCurrentItem() + 1, true);
            mHandler.postDelayed(mRunnable, getInterval());
        }
    }

    public HOverlapCardViewPager(@NonNull Context context) {
        super(context);
    }

    public HOverlapCardViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.HBannerViewPager);

        if (typedArray.hasValue(R.styleable.HOverlapCardViewPager_bvp_interval)) {
            mInterval = typedArray.getInteger(R.styleable.HOverlapCardViewPager_bvp_interval, 5000);
        }
        if (typedArray.hasValue(R.styleable.HOverlapCardViewPager_bvp_auto_play)) {
            isAutoPlay = typedArray.getBoolean(R.styleable.HOverlapCardViewPager_bvp_auto_play, false);
        }
        typedArray.recycle();
    }

    /**
     * 设置Adapter, 必须继承 HBaseViewPagerAdapter类
     *
     * @param adapter HBaseViewPagerAdapter
     */
    @Override
    public void setAdapter(@Nullable PagerAdapter adapter) {
        if (adapter instanceof HBaseViewPagerAdapter) {
            mBannerPagerAdapter = (HBaseViewPagerAdapter<T>) adapter;
            super.setAdapter(mBannerPagerAdapter);
        } else {
            throw new IllegalArgumentException("请使用HBaseViewPagerAdapter适配器");
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        if (isAttachedToWindow() || !isStopLoopWhenDetachedFromWindow()) {
            startLoop();
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        stopLoop();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        stopLoop();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isLooping = true;
                stopLoop();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
                isLooping = false;
                startLoop();
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }


    @Override
    protected void onDetachedFromWindow() {
        if (isStopLoopWhenDetachedFromWindow()) {
            stopLoop();
        }
        super.onDetachedFromWindow();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (isStopLoopWhenDetachedFromWindow()) {
            startLoop();
        }
    }

    private boolean isStopLoopWhenDetachedFromWindow() {
        return stopLoopWhenDetachedFromWindow;
    }

    /**
     * @param stopLoopWhenDetachedFromWindow 当BVP滑动出屏幕的时候是否要停止轮播，
     *                                       <p>
     *                                       true:滑动出屏幕停止自动轮播，false:滑动出屏幕继续自动轮播。默认值为true
     */
    public HOverlapCardViewPager<T> stopLoopWhenDetachedFromWindow(boolean stopLoopWhenDetachedFromWindow) {
        this.stopLoopWhenDetachedFromWindow = stopLoopWhenDetachedFromWindow;
        return this;
    }

    /**
     * Start loop
     */
    public void startLoop() {
        if (!isLooping && isAutoPlay() && mBannerPagerAdapter != null &&
                mBannerPagerAdapter.getListSize() > 1) {
            mHandler.postDelayed(mRunnable, getInterval());
            isLooping = true;
        }
    }

    /**
     * Start loop immediately
     */
    public void startLoopNow() {
        if (!isLooping && isAutoPlay() && mBannerPagerAdapter != null &&
                mBannerPagerAdapter.getListSize() > 1) {
            mHandler.post(mRunnable);
            isLooping = true;
        }
    }

    /**
     * Stop loop
     */
    public void stopLoop() {
        if (isLooping) {
            mHandler.removeCallbacks(mRunnable);
            isLooping = false;
        }
    }

    public long getInterval() {
        return mInterval;
    }

    public void setInterval(long interval) {
        mInterval = interval;
    }
}
